package com.alpha.common.utils.storage;

import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class LocalStorage {

    private final StorageProperties storageProperties;

    @Autowired
    public LocalStorage(StorageProperties storageProperties) {
        this.storageProperties = storageProperties;
    }

    public String getBaseUrl() {
        return storageProperties.getLocalSet().getHost() + storageProperties.getLocalSet().getStoragePath();
    }

    
    public void store(String fileName, String prefix, String suffix, InputStream inputStream) {
        try {
            Files.copy(inputStream, load(fileName), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException("保存文件失败 " + fileName, e);
        }
    }

    
    public String getByKey(String fileName) {
        return storageProperties.getLocalSet().getHost() + storageProperties.getLocalSet().getStoragePath() + "/" +fileName;
    }

    
    public void deleteByKey(String fileName) {
        Path file = load(fileName);
        try {
            Files.delete(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Path load(String fileName) {
        return storageProperties.getLocalSet().getRootPath().resolve(fileName);
    }
}
